package favorite_logic

import (
	"context"
	"errors"
	"fmt"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
)

type FavoriteLogic struct {
	Ctx context.Context
}

func NewFavoriteLogic(ctx context.Context) *FavoriteLogic {
	return &FavoriteLogic{Ctx: ctx}
}

// CreateFavorite 创建收藏
func (l *FavoriteLogic) CreateFavorite(userId int64, req *dto.CreateFavoriteReq) error {
	// 检查收藏类型是否有效
	if !isValidFavoriteType(req.Type) {
		return errors.New("无效的收藏类型")
	}

	// 检查是否已收藏
	exists, err := models.Exists(l.Ctx, &models.UserFavorite{},
		"user_id = ? AND type = ? AND target_id = ? AND status = ?",
		userId, req.Type, req.TargetId, models.FavoriteStatusNormal)
	if err != nil {
		return err
	}
	if exists {
		return errors.New("已收藏该内容")
	}

	// 创建收藏记录
	favorite := &models.UserFavorite{
		UserId:   userId,
		Type:     req.Type,
		TargetId: req.TargetId,
		Title:    req.Title,
		Cover:    req.Cover,
		Remark:   req.Remark,
		Status:   models.FavoriteStatusNormal,
	}

	_, err = models.Insert(l.Ctx, favorite)
	return err
}

// UpdateFavorite 更新收藏
func (l *FavoriteLogic) UpdateFavorite(userId int64, req *dto.UpdateFavoriteReq) error {
	// 查询收藏是否存在
	favorite := new(models.UserFavorite)
	exists, err := models.Get(l.Ctx, favorite, "id = ? AND user_id = ?", req.Id, userId)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("收藏不存在")
	}

	// 更新字段
	if req.Remark != "" {
		favorite.Remark = req.Remark
	}
	if req.Status > 0 {
		favorite.Status = req.Status
	}

	return models.Update(l.Ctx, fmt.Sprintf("id = %d", req.Id), favorite)
}

// DeleteFavorite 删除收藏
func (l *FavoriteLogic) DeleteFavorite(userId int64, id int64) error {
	// 查询收藏是否存在
	favorite := new(models.UserFavorite)
	exists, err := models.Get(l.Ctx, favorite, "id = ? AND user_id = ?", id, userId)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("收藏不存在")
	}

	// 软删除，更新状态为已取消
	favorite.Status = models.FavoriteStatusDisabled
	return models.Update(l.Ctx, fmt.Sprintf("id = %d", id), favorite)
}

// ListFavorite 查询收藏列表
func (l *FavoriteLogic) ListFavorite(userId int64, req *dto.ListFavoriteReq) (*dto.ListFavoriteResp, error) {
	where := "user_id = ?"
	var params []interface{}
	params = append(params, userId)

	// 添加查询条件
	if req.Type != "" {
		where += " AND type = ?"
		params = append(params, req.Type)
	}
	if req.Status > 0 {
		where += " AND status = ?"
		params = append(params, req.Status)
	}

	// 获取总数
	total, err := models.Count(l.Ctx, &models.UserFavorite{}, where, params...)
	if err != nil {
		return nil, err
	}

	// 获取列表
	var favorites []*models.UserFavorite
	_, err = models.FindByPage(l.Ctx, &favorites, req.Page, req.Size, where, params...)
	if err != nil {
		return nil, err
	}

	// 转换响应
	list := make([]*dto.FavoriteResp, len(favorites))
	for i, favorite := range favorites {
		list[i] = &dto.FavoriteResp{
			Id:         favorite.Id,
			Type:       favorite.Type,
			TargetId:   favorite.TargetId,
			Title:      favorite.Title,
			Cover:      favorite.Cover,
			Remark:     favorite.Remark,
			Status:     favorite.Status,
			CreateTime: favorite.CreateTime.Format("2006-01-02 15:04:05"),
		}
	}

	return &dto.ListFavoriteResp{
		Total: total,
		List:  list,
	}, nil
}

// isValidFavoriteType 检查收藏类型是否有效
func isValidFavoriteType(favoriteType string) bool {
	switch favoriteType {
	case models.FavoriteTypeProduct,
		models.FavoriteTypeArticle,
		models.FavoriteTypeVideo:
		return true
	default:
		return false
	}
}
